package com.javaclimb.controller;

import com.javaclimb.pojo.SysUser;
import com.javaclimb.service.SysUserService;
import com.javaclimb.util.Consts;
import com.javaclimb.util.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    //调用service层
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/")
    public String rootUrl() {
        return "redirect:login";
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request) {
        return "login";
    }

    //当用户点击登陆，通过ajax跳转到这里(需要返回一个json数据，可能用户点击了记住密码把账号密码存放到cookie里面)
    @RequestMapping("requestLogin")
    @ResponseBody //返回json格式
    public ReturnData requestLogin(SysUser user,HttpServletRequest request){
        //如果session里面有这个用户的话直接登录即可
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute(Consts.SYS_USER_INFO);//获取登陆用户名
        //判断有用户名(有的话直接登录成功)
        if(sysUser!=null){
            return ReturnData.success("登陆成功");
        }
        //把前端传递过来的user和request传递到service
        return sysUserService.login(user,request);
    }

    /**
     * 后台首页(也要把用户名给带着)
     * */
    @RequestMapping("index")
    public String index(HttpServletRequest request){
        return "index";
    }

    /**
     * 后台用户退出(清除session然后退出到登录页面即可)
     * */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        //把sessio里面的用户值给清空
        session.setAttribute(Consts.SYS_USER_INFO,null);
        //不需要传递任何值到登录页面，所以用重定向最好
        return "redirect:login";
    }



}
